package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.entity.PageResult;
import com.itheima.health.mapper.CheckItemMapper;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.service.CheckItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Program: review2-health
 * @ClassName: CheckItemServiceImpl
 * @Description:
 * @Author: KyleSun
 **/
@Service
@Slf4j
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    private CheckItemMapper checkItemMapper;

    @Override
    public List<CheckItem> findAll() {
        return checkItemMapper.findAll();
    }

    @Override
    public CheckItem findOne(Integer id) {
        return checkItemMapper.findOne(id);
    }

    @Override
    public CheckItem add(CheckItem checkItem) {

        if (checkItem == null || checkItem.getId() == null) {
            log.error("CheckItemServiceImpl add is error,caused by checkItem={}", checkItem);
            throw new RuntimeException("新增检查项失败");
        }

        checkItemMapper.add(checkItem);
        return checkItem;
    }

    @Override
    public void delete(Integer id) {
        checkItemMapper.delete(id);
    }

    @Override
    public CheckItem update(Integer id, CheckItem checkItem) {

        if (id == null) {
            log.error("CheckItemServiceImpl update is error,caused by id is null");
            throw new RuntimeException("主键不能为空！");
        }

        CheckItem item = checkItemMapper.findOne(id);
        if (item == null) {
            log.error("CheckItemServiceImpl update is error,caused by id is null");
            throw new RuntimeException("无此检查项！");
        }

        checkItem.setId(id);
        checkItemMapper.update(checkItem);

        return checkItem;
    }

    @Override
    public PageResult<CheckItem> search(CheckItem checkItem, Integer page, Integer size) {

        if (page == null) page = 1;
        if (size == null) size = 10;

        PageHelper.startPage(page, size);

        Page<CheckItem> pageResult = (Page<CheckItem>) checkItemMapper.search(checkItem);
        long total = pageResult.getTotal();
        int totalPages = pageResult.getPages();
        List<CheckItem> rows = pageResult.getResult();

        return new PageResult<>(totalPages, total, rows);
    }
}
